package 剑指offer;

public class _22链表中倒数第k个节点 {
  public class ListNode {
     int val;
     ListNode next;
     ListNode(int x) { val = x; }
 }
    public ListNode getKthFromEnd(ListNode head, int k) {
        if(head == null || k == 0){
            return head;
        }
        ListNode fast = head;
        ListNode slow = head;

//        for (int i = 0; i < k - 1; i++) {
//            if(fast.next != null){
//                fast = fast.next;
//            }else {//防止k大于链表长度
//                return null;
//            }
//        }
        while (k > 0 && fast != null){
            fast = fast.next;
            k--;
        }
        if (k > 0){
            return null;
        }
        while (fast != null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}
